const fs = require('fs');
const path = require('path');



const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();

app.use(bodyParser.json());
app.use(cors());

app.get('/api', (req, res) => {


  function getDirectoryStructure(dirPath) {
    const dirStructure = {};
   
    const files = fs.readdirSync(dirPath);
    files.forEach(file => {
      const filePath = path.join(dirPath, file);
      const stats = fs.statSync(filePath);
   
      if (stats.isDirectory()) {
        dirStructure[file] = getDirectoryStructure(filePath);
      } else {
        dirStructure[file] = stats.size;
      }
    });
   
    return dirStructure;
  }
   
  const directoryPath = 'D:\/data\/demo-data';
  const directoryStructure = getDirectoryStructure(directoryPath);
  
  function getFiles(dataTree, formats, basePath = "") {
    const resList = [];
    for(let key in dataTree) {
      const files = dataTree[key];
      if(!Object.prototype.toString.apply(files).toLowerCase().includes("number")) {
        resList.push(...getFiles(files, formats, basePath + "/" + key));
      } else if(formats.includes(key.slice(key.lastIndexOf(".")))) {
        resList.push(basePath + "/" + key);
      }
    }
    return resList;
  }

  const resultFiles = getFiles(directoryStructure, [".mp4"]);
  console.log(resultFiles);
  
  res.send(JSON.stringify(resultFiles.map(item => directoryPath + item)));
});

app.get('/api2', (req, res) => {
  fs.readFile(`D:/data/demo-data/去他妈的世界第一季/去他妈的世界第一季01.mp4`, (err, data) => {
    if(err) {
      throw err;
    } else {
      res.send(data);
    }
  });
});

app.listen(3000, () => {
  console.log("server started on port 3000");
})